<template>
  <div class='addBan'>

    <el-form ref="addFormRef" :model="addBanForm" :rules="addBanRules" label-width="120px" size="large" @submit.prevent>

      <el-form-item label='班课名称：' prop="name">
        <el-input v-model.trim="addBanForm.name" placeholder="请填写班课名称" />
      </el-form-item>
      <el-form-item label='专业方向：' prop="marjor_id">
        <el-select v-model="addBanForm.marjor_id" placeholder="请选择专业方向">
          <el-option v-for="item in majordArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>


      <el-form-item label='适用班级：' prop="cla_id">
        <el-select v-model="addBanForm.cla_id" placeholder="请选择适用班级">
          <el-option v-for="item in classListData" :key="item.id" :label="item.cla_name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label='封面：' prop='cover_url'>
        <div class='cover'>
          <div class='upload'>

            <div class='cover-uploader' @click='editCover'>
              <div class='view'>
                <img :src='addBanForm.cover_url' class='thumbnail' alt='' v-if='addBanForm.cover_url'>
                <div v-else>点击添加缩略图</div>
              </div>

              <div class='ceng'>
                <span class='iconfont icon-jiahao1'></span>
              </div>
            </div>

            <BanDialog v-model:dialogVisible='dialogVisible' width='1000px' title='修改封面'>
              <template #content>
                <div class='popCover'>
                  <CropperImage @coverEvent='coverEvent' :bkCover='addBanForm.cover_url'></CropperImage>
                </div>
              </template>
            </BanDialog>
          </div>

        </div>
      </el-form-item>
      <el-form-item>
        <div class='btngroup'>
          <el-button type='primary' :disabled="isDisabled"  :loading="loadingRef" @click='submitForm'>
            {{ banId ? '修改班课' : '创建班课' }}
          </el-button>
          <el-button :disabled="loadingRef" @click='resetForm'>取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import BanDialog from '@/components/BanDialog.vue';
import CropperImage from '@/components/CropperImage.vue';
import { upclass, addclass, classrow } from '@/api/banke/class';
import { appclaList } from "@/api/banji/classadmin.js"
const majordArr=ref([])
//获取父组件传过来的值
const props = defineProps({
  bkitem: {
    type: Object,
    default: () => ({})
  },

  banId: {
    type: Number
  },

  majorListData: {
    type: Array
  }

});



watch(() => props.banId, (nv) => {
  if (nv) {
    classrow(nv).then(res => {
  //解决从资源库拷贝至班课专业方向绑定异常的bug
// res.marjor_id是否存在于majordArr.value专业方向数组中，如果不存在则将其设置为空
  res.marjor_id = majordArr.value.some(item => item.id === res.marjor_id) ? res.marjor_id : '';
      addBanForm.value = res
    })
  }

}, {
  immediate: true, // 立即执行一次回调函数
  deep: true,
}
)



watch(() => props.majorListData, (nv) => {
  majordArr.value = nv.filter(item => item.id !== '');
  console.log(nv);
  

}, {
  immediate: true, // 立即执行一次回调函数
  deep: true,
}
)

const { proxy } = getCurrentInstance();
const selectLoadingRef = ref(false)
const loadingRef = ref(false)
const isDisabled=ref(false)
const courseListRef = ref([])
const classListData = ref([])
//获取表单dom
const addFormRef = shallowRef(null)
const dialogVisible = ref(false);
const emits = defineEmits(['addEvent', 'addSuccess']);


console.log(props.bkitem);

//添加班课表结构
const addBanForm = ref({
  name: props.bkitem.name,
  marjor_id:props.bkitem.marjor_id,
  cla_id: props.bkitem.cla_id,
  cover_id: props.bkitem.cover_id,
  cover_url:props.bkitem.cover_url
});


//表结构验证规则
const addBanRules = ref({

  name: [
    { required: true, message: '班课名称必须填写' },
    { min: 2, max: 15, message: '班课名称在2到15位之间', trigger: 'blur' }
  ],
  marjor_id: [
    { required: true, message: '专业方向必须选择' },
  ],
  cla_id: [
    { required: true, message: '适用班级必须选择' },
  ],
  cover_url: [
    { required: true, message: '班课封面必须制作' },
  ],
});

//编辑封面
const editCover = () => {
  // console.log(addBanForm.value.cover_url.indexOf('.jpg') == -1);
  
  if (addBanForm.value.cover_url) {
    if (addBanForm.value.cover_url.indexOf('.jpg') == -1) {
      dialogVisible.value = true;
      return;
    }

    dialogVisible.value = true;

  } else {
    dialogVisible.value = true;
  }

};


//封面编辑完毕之后
const coverEvent = (coverUrl, coverId) => {
  dialogVisible.value = false;
  addBanForm.value.cover_url = coverUrl
  addBanForm.value.cover_id = coverId
};


//提交新增班课表单
const submitForm = () => {

  proxy.$refs.addFormRef.validate(valid => {
    let options = {
      name: addBanForm.value.name,
      marjor_id: addBanForm.value.marjor_id + '',
      cla_id: addBanForm.value.cla_id,
      cover_id: addBanForm.value.cover_id
    }

    if (valid) {
      loadingRef.value = true
      if (!addBanForm.value.id) { 
        console.log(options);
        addclass(options).then(res => {  
          console.log(res);    
          if(res){
            ElMessage.success('添加成功');
            loadingRef.value = false   
            emits('addSuccess')
            isDisabled.value=false
          }else{
            ElMessage.error(res.response.data);
            loadingRef.value = false
          }
          
        })
      } else {
        console.log(options);
        options.id = props.banId + ''
        console.log(options);
        loadingRef.value = true
        upclass(options).then(res => {

          ElMessage.success('修改成功');
          loadingRef.value = false
          emits('addSuccess')
        })
      }
    } else {
      ElMessage.error('请按要求填写');
    }
  });
};


//重置表单
const resetForm = () => {
  proxy.$refs.addFormRef.resetFields();
  emits('addEvent');
};



// 老师适用班级列表
const classData = () => {
  let params = {
    page_size: "20",
    page_num: "1"
  }
  appclaList().then(res => {
    console.log(res);

    classListData.value = res

  })
}

classData()
</script>


<style lang='scss' scoped>
.popCover {
  min-height: 400px;
}


.addBan {
  padding: 0 30px;

  .tips {
    font-size: 14px;
    color: rgba(153, 153, 153, 1);

    .iconfont {
      margin: 0 8px 0 15px;
      color: rgba(67, 149, 255, 1);
    }
  }

  .el-form-item {
    padding: 5px 0;
  }

  .cover {
    display: flex;
  }

  .upload {
    width: 200px;
    height: 113px;

    .cover-uploader {
      width: 100%;
      height: 100%;
      border: 1px dashed #ccc;
      border-radius: 6px;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      position: relative;
      cursor: pointer;

      .view {
        img {
          width: 100%;
          height: 100%;
          display: block;
        }

        div {
          font-size: 14px;
          color: #999
        }
      }

      .ceng {
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.7);
        color: #fff;
        position: absolute;
        top: 0;
        left: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        opacity: 0;

        .iconfont {
          font-size: 40px;
        }
      }

    }

    .cover-uploader:hover {
      border-color: #4395FF;

      .ceng {
        opacity: 1;
      }
    }
  }

  .text {
    padding-left: 30px;
    line-height: 1.7em;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .top {
      font-size: 16px;
      color: #4395FF;
      cursor: pointer;

      .iconfont {
        font-size: 22px;
        vertical-align: middle;
      }
    }

    .top:hover {
      color: #175CEB;
    }

    .btm {
      font-size: 13px;
      color: #999;
    }
  }

  .btngroup {
    padding-top: 30px;
  }
}
</style>
